package com.lbd.system.controller;

import com.lbd.base.controller.BaseController;
import com.lbd.commons.Result;
import com.lbd.commons.ResultState;
import com.lbd.system.bean.Employee;
import com.lbd.system.bean.Menu;
import com.lbd.system.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by WangYajie on 2016/9/19.
 */
@RestController
@RequestMapping("/menu")
public class MenuController extends BaseController {

    @Autowired
    MenuService menuService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result list(int page, int rows, Menu menu) {
        return new Result(ResultState.SUCCESS, "查询成功", menuService.findByPageConditionJpql(page, rows, menu));
    }

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public Result list() {
        List<Menu> result = new ArrayList<>();
        List<Menu> menus = menuService.findByParentIsNull();
        for (Menu menu : menus) {
            result.add(menu);
            result.addAll(menu.getChildren());
            menu.setChildren(null);
            menu.setParent(null);
        }
        return new Result(ResultState.SUCCESS, "查询成功", result);
    }

    /**
     * 加载用户菜单
     *
     * @return
     */
    @RequestMapping(value = "/loadMenu", method = RequestMethod.GET)
    public Result loadMenu(HttpSession session) {
        Employee employee = (Employee) session.getAttribute(Employee.SESSION_USER);
        return new Result(ResultState.SUCCESS, "查询成功", menuService.loadUserMenu(employee.getId()));
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Result save(Menu menu) {
        menuService.save(menu);
        return new Result(ResultState.SUCCESS, "添加成功", "");
    }

    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result del(@RequestParam("ids[]") String[] ids) {
        System.out.println(Arrays.toString(ids));
        menuService.del(ids);
        return new Result(ResultState.SUCCESS, "删除成功", "");

    }

    /**
     * 加载授权树
     *
     * @return
     */
    @RequestMapping(value = "/authorityTree")
    public Result tree() {
        List<Menu> menus = menuService.findByParentIsNull();
        return new Result(ResultState.SUCCESS, "查询成功", menus);
    }

    /**
     * 获取所父分类菜单
     */
    public Result parents() {
        List<Menu> menus = menuService.findByParentIsNull();
        return new Result(ResultState.SUCCESS, "查询成功", menus);
    }
}
